<template>
  <div class="works-container" :class="{ 'random-mode': isRandom }">
    <RandomModeBar 
      v-if="isRandom"
      :writer-name="writer?.name"
    />

    <div class="section">
      <h1>
        <img v-if="isRandom" src="@/assets/img/random.png" class="random-icon" alt="随机">
        作品
      </h1>
      <ul class="clearfix">
        <li v-for="work in novels" :key="work.id">
          <div class="work-container">
            <div class="work-image-container">
              <a :href="work.detail_url || '#'" target="_blank">
                <img :src="getImageUrl(work)" />
              </a>
              <button v-if="isLoggedIn" class="edit-work-btn" @click.stop="editWork(work.id)">
                <i class="el-icon-edit"></i>
              </button>
            </div>
            <div class="image_title">
              <span class="title-text">{{ work.title }}</span>
            </div>
          </div>
        </li>
        <li v-if="isLoggedIn" class="add-work-card" @click="addWork(0)">
          <div class="add-work-plus">+</div>
          <div class="image_title"><a>增加作品...</a></div>
        </li>
      </ul>
    </div>

    <div class="section">
      <h1>
        <img v-if="isRandom" src="@/assets/img/random.png" class="random-icon" alt="随机">
        传记
      </h1>
      <ul class="clearfix">
        <li v-for="work in biographies" :key="work.id">
          <div class="work-container">
            <div class="work-image-container">
              <a :href="work.detail_url || '#'" target="_blank">
                <img :src="getImageUrl(work)" />
              </a>
              <button v-if="isLoggedIn" class="edit-work-btn" @click.stop="editWork(work.id)">
                <i class="el-icon-edit"></i>
              </button>
            </div>
            <div class="image_title">
              <span class="title-text">{{ work.title }}</span>
            </div>
          </div>
        </li>
        <li v-if="isLoggedIn" class="add-work-card" @click="addWork(1)">
          <div class="add-work-plus">+</div>
          <div class="image_title"><a>增加作品...</a></div>
        </li>
      </ul>
    </div>

  </div>
</template>

<script>
import RandomModeBar from '@/components/RandomModeBar.vue'

export default {
  name: 'Works',
  components: {
    RandomModeBar
  },
  data() {
    return {
      works: [],
      writerId: null,
      writer: null,
      backendUrl: 'http://localhost:3000',
      isRandom: false
    }
  },
  computed: {
    isLoggedIn() {
    return !!localStorage.getItem('token')
    },
    novels() {
      return this.works.filter(w => w.is_biography == 0)
    },
    biographies() {
      return this.works.filter(w => w.is_biography == 1)
    }
  },
  methods: {
    getImageUrl(work) {
      if (work.cover_path) {
        return `${this.backendUrl}${work.cover_path}`;
      }
      return require(`@/assets/img/defaultCover.jpg`);
    },
    addWork(isBiography) {
      if (this.writerId) {
        this.$router.push(`/edit-work?writerId=${this.writerId}&is_biography=${isBiography}&from=${encodeURIComponent(this.$route.fullPath)}`);
      } else {
        this.$router.push(`/edit-work?is_biography=${isBiography}&from=${encodeURIComponent(this.$route.fullPath)}`);
      }
    },
    getTruncatedTitle(title) {
    const maxChars = 12; // 大约能显示的字符数
    return title.length > maxChars ? `${title.substring(0, maxChars)}...` : title;
    },
    editWork(workId) {
    this.$router.push(`/edit-work/${workId}`);
    },
    async fetchWorks() {
    this.writerId = this.$route.params.writerId || null;
    this.isRandom = this.$route.query.mode === 'random';
    
    try {
        const url = this.writerId ? `/api/works/writer/${this.writerId}` : '/api/works/all';
        const response = await this.$axios.get(url);

        if (this.writerId) {
          this.works = response.data.works || [];
          // 如果是探索模式，需要获取作家信息
          if (this.isRandom) {
            await this.fetchWriter();
          }
        } else {
          this.works = Array.isArray(response.data) ? response.data : [];
        }
      } catch (e) {
        console.error('获取作品失败:', e);
        this.works = [];
      }
    },
    async fetchWriter() {
      if (!this.writerId) return;
      try {
        const response = await this.$axios.get(`/api/writers/${this.writerId}`);
        this.writer = response.data;
      } catch (error) {
        console.error('获取作家信息失败：', error);
      }
    }
  },
  created() {
    this.fetchWorks();
  },
  beforeRouteUpdate(to, from, next) {
  this.writerId = to.params.writerId || null;
  this.isRandom = to.query.mode === 'random';
  this.fetchWorks();
  next();
  }
}
</script>

<style scoped>
@import '~@/assets/css/works.css';

.random-icon {
  width: 24px;
  height: 24px;
  margin-right: 10px;
  vertical-align: middle;
}

.add-work-card {
  float: left;
  list-style: none;
  width: 100px;
  height: 150px; 
  transition: all .8s;
  position: relative;
  overflow: hidden;
  border: 2px dashed #166d80;
  box-shadow: 0px 0px 20px rgba(0,0,0,0.8);
  margin-left: 10px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
}

.add-work-card:hover {
  border-style: solid;
  background-color: white;
}

.add-work-plus {
  font-size: 50px;
  color: #166d80;
  font-weight: bold;
}

.add-work-card .image_title {
  position: absolute;
  width: 100%;
  height: 20px;
  background-color: rgba(0,0,0,.5);
  font-size: x-small;
  line-height: 20px;
  bottom: 0px;
  left: 0;
  text-transform: uppercase;
  text-align: center;
}

.add-work-card .image_title a {
  color: #fff;
  text-decoration: none;
}

.novel ul li img, .biography ul li img {
    width: 150px;
    height: 150px;
    object-fit: cover;
}

.works-container {
  padding-bottom: 50px;
}
.work-image-container {
  position: relative;
  display: inline-block;
}

.edit-work-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 24px;
  height: 24px;
  background-color: rgba(255, 255, 255, 0.8);
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  z-index: 10;
}

.edit-work-btn:hover {
  background-color: white;
}

.edit-work-btn i {
  font-size: 14px;
  color: #166d80;
}
</style> 